import React, { useState, useEffect } from 'react';
import { Card, List, Avatar, Tag, Typography, Divider, Spin, message, Input, Button, Modal } from 'antd';
import { SearchOutlined, DownloadOutlined, ShoppingOutlined, AppstoreOutlined, EyeOutlined, WechatOutlined } from '@ant-design/icons';
import axios from 'axios';

const { Title, Paragraph, Text } = Typography;
const { Search } = Input;

// 假设的客服信息，实际项目中可能从配置或API获取
const CUSTOMER_SERVICE = {
  name: '客服小姐姐',
  avatar: 'https://joeschmoe.io/api/v1/random',
  qrcode: 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=https://weixin.qq.com'
};

const MarketPage = () => {
  const [plugins, setPlugins] = useState([]);
  const [filteredPlugins, setFilteredPlugins] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchText, setSearchText] = useState('');
  const [rechargeModalVisible, setRechargeModalVisible] = useState(false);
  const [downloadLoading, setDownloadLoading] = useState(false);
  const [activePluginId, setActivePluginId] = useState(null);

  useEffect(() => {
    const fetchPlugins = async () => {
      try {
        setLoading(true);
        // 从公共目录加载market_plugins.json文件
        const response = await axios.get('/data/market_plugins.json');
        console.log('市场插件数据:', response.data);
        setPlugins(response.data);
        setFilteredPlugins(response.data);
      } catch (error) {
        console.error('加载市场插件列表失败:', error);
        message.error('加载市场插件列表失败');
      } finally {
        setLoading(false);
      }
    };

    fetchPlugins();
  }, []);

  // 处理搜索
  const handleSearch = (value) => {
    setSearchText(value);
    
    if (!value.trim()) {
      setFilteredPlugins(plugins);
      return;
    }
    
    const searchLower = value.toLowerCase();
    const filtered = plugins.filter(plugin => 
      plugin.name.toLowerCase().includes(searchLower) || 
      plugin.type.toLowerCase().includes(searchLower) || 
      plugin.description.toLowerCase().includes(searchLower) ||
      plugin.author.toLowerCase().includes(searchLower)
    );
    
    setFilteredPlugins(filtered);
  };

  // 获取用户余额
  const fetchUserBalance = async () => {
    try {
      const response = await axios.get('http://127.0.0.1:8081/user/balance');
      return response.data.balance;
    } catch (error) {
      console.error('获取用户余额失败:', error);
      message.error('获取用户余额失败');
      return null;
    }
  };

  // 下载插件
  const handleDownload = async (plugin) => {
    setDownloadLoading(true);
    setActivePluginId(plugin.id);
    try {
      console.log('下载插件:', plugin);
      
      // 获取用户余额
      const balance = await fetchUserBalance();
      if (balance === null) {
        setDownloadLoading(false);
        setActivePluginId(null);
        return; // 获取余额失败，已经在fetchUserBalance中显示错误信息
      }
      
      // 获取插件价格
      const pluginPrice = plugin.price === '免费' ? 0 : parseInt(plugin.price.replace('￥', ''));
      
      // 检查余额是否充足
      if (balance >= pluginPrice) {
        // 余额充足，提示添加成功
        message.success(`添加成功: ${plugin.name}`);
        // 这里可以添加实际的下载或添加逻辑
      } else {
        // 余额不足，显示充值弹窗
        setRechargeModalVisible(true);
      }
    } catch (error) {
      console.error('添加插件失败:', error);
      message.error('添加插件失败');
    } finally {
      setDownloadLoading(false);
      setActivePluginId(null);
    }
  };

  // 打开预览链接
  const handlePreview = () => {
    window.open('https://www.baidu.com', '_blank');
  };

  // 根据插件类型获取不同的颜色
  const getTagColor = (type) => {
    const colorMap = {
      '抖音': 'magenta',
      '王者荣耀': 'green',
      '快手': 'orange',
      '微信': 'cyan',
      '微博': 'blue',
      // 可以根据需要添加更多类型的颜色
    };
    
    return colorMap[type] || 'blue';
  };

  // 格式化下载量
  const formatDownloadCount = (count) => {
    if (count >= 10000) {
      return (count / 10000).toFixed(1) + 'w+';
    }
    return count + '+';
  };

  return (
    <Card bordered={false} bodyStyle={{ padding: '24px' }}>
      {/* 全局Loading指示器 */}
      {downloadLoading && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          background: 'rgba(255, 255, 255, 0.6)',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          zIndex: 9999
        }}>
          <Spin size="large" tip="请稍候..." />
        </div>
      )}
      
      <div style={{ marginBottom: '34px', display: 'flex', justifyContent: 'center' }}>
        <Search
          placeholder="搜索插件名称、类型、描述..."
          allowClear
          enterButton={<SearchOutlined />}
          size="large"
          onSearch={handleSearch}
          onChange={(e) => handleSearch(e.target.value)}
          style={{ width: '100%', maxWidth: '800px' }}
        />
      </div>
      
      {loading ? (
        <div style={{ textAlign: 'center', padding: '40px 0' }}>
          <Spin size="large" />
        </div>
      ) : filteredPlugins.length > 0 ? (
        <List
          grid={{ 
            gutter: 24, 
            xs: 1, 
            sm: 2, 
            md: 3, 
            lg: 3, 
            xl: 4, 
            xxl: 4 
          }}
          dataSource={filteredPlugins}
          renderItem={plugin => (
            <List.Item>
              <Card
                hoverable
                style={{ borderRadius: '8px', height: '100%' }}
              >
                <div style={{ marginBottom: '12px', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                  <Tag color={getTagColor(plugin.type)}>
                    {plugin.type}
                  </Tag>
                  <EyeOutlined 
                    style={{ fontSize: '18px', cursor: 'pointer' }}
                    onClick={handlePreview}
                  />
                </div>
                <Title level={4} style={{ marginTop: '0' }}>{plugin.name}</Title>
                <Paragraph type="secondary" style={{ height: '40px', overflow: 'hidden' }}>
                  {plugin.description}
                </Paragraph>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
                  <Text type="secondary">
                    <DownloadOutlined style={{ marginRight: '4px' }} />
                    {formatDownloadCount(plugin.download_count)}
                  </Text>
                  <Text style={{ 
                    color: plugin.price === '免费' ? '#52c41a' : '#f5222d', 
                    fontWeight: 'bold' 
                  }}>
                    {plugin.price === '免费' ? (
                      plugin.price
                    ) : (
                      <>
                        <ShoppingOutlined style={{ marginRight: '4px' }} />
                        {plugin.price}
                      </>
                    )}
                  </Text>
                </div>
                <Divider style={{ margin: '12px 0' }} />
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <Avatar 
                      size="small" 
                      src={plugin.avatar} 
                      style={{ marginRight: '8px' }} 
                      icon={<AppstoreOutlined />}
                    />
                    <span>{plugin.author}</span>
                  </div>
                  <Button 
                    type="primary" 
                    size="small"
                    onClick={() => handleDownload(plugin)}
                    disabled={downloadLoading}
                  >
                    添加
                  </Button>
                </div>
              </Card>
            </List.Item>
          )}
        />
      ) : (
        <div style={{ textAlign: 'center', padding: '40px 0' }}>
          {searchText ? (
            <Typography.Text type="secondary">未找到匹配的插件</Typography.Text>
          ) : (
            <Typography.Text type="secondary">暂无插件数据</Typography.Text>
          )}
        </div>
      )}

      {/* 充值弹窗 */}
      <Modal
        title={null}
        open={rechargeModalVisible}
        onCancel={() => setRechargeModalVisible(false)}
        footer={null}
        width={400}
        centered
        closable={true}
        bodyStyle={{ padding: '30px 20px' }}
        className="recharge-modal"
      >
        <div style={{ textAlign: 'center' }}>
          <div style={{ 
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            marginBottom: '25px',
            width: '100%'
          }}>
            <Avatar 
              size={50} 
              src={CUSTOMER_SERVICE.avatar}
              icon={<WechatOutlined style={{ color: '#09bb07' }} />}
              style={{ 
                border: '2px solid #f0f0f0',
                backgroundColor: '#fff',
                marginRight: '12px',
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)'
              }}
            />
            <div style={{ textAlign: 'left' }}>
              <Title level={4} style={{ margin: '0 0 4px 0', fontSize: '18px' }}>{CUSTOMER_SERVICE.name}</Title>
              <div style={{ 
                color: '#595959', 
                fontSize: '14px',
                backgroundColor: '#f5f5f5',
                padding: '4px 8px',
                borderRadius: '4px',
                display: 'inline-block'
              }}>
                微信扫码充值
              </div>
            </div>
          </div>
          
          <div style={{ 
            margin: '20px auto', 
            width: 200, 
            height: 200,
            padding: '10px',
            border: '1px solid #eaeaea',
            borderRadius: '8px',
            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08)'
          }}>
            <img 
              src={CUSTOMER_SERVICE.qrcode} 
              alt="微信二维码" 
              style={{ width: '100%', height: '100%', objectFit: 'cover' }}
            />
          </div>
          
          <Paragraph style={{ margin: '16px 0', color: '#888' }}>
            <small>扫码添加，备注"充值"</small>
          </Paragraph>
          
          <Button 
            type="primary" 
            size="large"
            onClick={() => setRechargeModalVisible(false)}
            style={{ 
              width: '80%', 
              marginTop: '10px',
              borderRadius: '6px',
              background: 'linear-gradient(90deg, #1890ff, #52c41a)',
              border: 'none',
              height: '46px'
            }}
          >
            我知道了
          </Button>
        </div>
      </Modal>
    </Card>
  );
};

export default MarketPage; 